<?php


namespace App\Cron\Command;


use App\Common\HttpClients;
use App\Common\Redis;
use App\Models\TextModel;
use App\Models\UserModel;
use EasySwoole\EasySwoole\Command\CommandInterface;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Core;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;
use Swoole\Coroutine;

class Test implements CommandInterface
{
    public $headers = [
        'Accept ' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    ];

    public function commandName(): string
    {
        return 'test'; //命令行名字
        // TODO: Implement commandName() method.
    }

    public function exec(array $args): ?string
    {

        $this->mysql_pool_conn();

//        Core::getInstance()->createServer();
//        var_dump($a);
//        UserModel::getInstance()->

//        $this->manyGoDow(); //多协程下载例子
//        $this->countOff();
//        $this->manyGoWeixin();
//        Redis::getInstance()->rpush('liuqiang',1111);
//        var_dump(UserModel::create()->where(['username'=>'root'])->select());
        go(function () {
            var_dump(UserModel::getInstance()->userFindOne('root'));
            return false;
        });


        //        多协程下载
//        foreach (range(0, 10) as $v) {
//            foreach (range(0, 100) as $vo) {
//                go(function () use ($v, $vo) {
//                    $this->http_req("http://audio.xmcdn.com/group49/M00/CD/41/wKgKl1vdR-SQixBDAEYaB27zQH8341.m4a");
//                    echo '协程id：' . $v . '第' . $vo . '次' . '下载成功' . PHP_EOL;
//                });
//            }
//            echo '协程id：' . $v . '开启成功' . PHP_EOL;
//
//        }
        return true;
    }

    /**
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    protected function manyGoWeixin()
    {

//        $wait = new \EasySwoole\Component\WaitGroup();

//        $wait->wait();
//        $chan->close();

    }


    protected function redisQueue()
    {

    }

    //管道使用示例
    protected function chan()
    {
        $chan = new \chan(50);
        go(function () use ($chan) {
            foreach (range(0, 1000) as $v) {
                $sendData = [
                    "touser" => 'oZ_cg1G5Jg1TCEdOGG-H2w2jzFeI',
                    "msgtype" => 'news',
                    'news' => unserialize('a:1:{s:8:"articles";a:2:{i:0;a:4:{s:3:"url";s:61:"http://wxx.324.com/wechat/review.html?content=55&type=article";s:5:"title";s:9:"新图文";s:5:"image";s:70:"http://wxx.324.com/static/upload/39e7ec21f5cafd7f/b49ee9bea10225bd.jpg";s:11:"description";s:45:"文章内容不能留空，请输入内容！";}i:1;a:4:{s:3:"url";s:61:"http://wxx.324.com/wechat/review.html?content=56&type=article";s:5:"title";s:9:"新图文";s:5:"image";s:70:"http://wxx.324.com/static/upload/b32906fb1f02264a/60b3224a7590c02f.jpg";s:11:"description";s:45:"文章内容不能留空，请输入内容！";}}}'),
                ];
                $chan->push($sendData);
            }
        });

        foreach (range(0, 100) as $v) {
            go(function () use ($chan) {
                while (true) {
                    $sendData = $chan->pop();
                    if ($sendData) {
                        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=464646464';
                        $res = HttpClients::getInstance()->http($url, $sendData, 'json');
                        echo $res, PHP_EOL;
                    } else {
                        Coroutine::sleep(1);
                        echo '睡眠', PHP_EOL;
                    }
                }
            });
        }

    }

    //多协程下载例子
    protected function manyGoDow()
    {
        $fileUrl = file_get_contents('mmm.txt');
        $arrayUrl = explode("\n", trim($fileUrl, "\n"));
        foreach (array_chunk($arrayUrl, 50) as $k => $chunkData) {
            go(function () use ($k, $chunkData) {
                foreach ($chunkData as $key => $v) {
                    $urlData = json_decode($v, true);
                    $res = $this->downloadFile($urlData['url'], 'vidio/' . $urlData['number'] . '.mp3');
                    echo '协程id：' . $k . '第' . $key . '次音频下载成功' . '下载成功' . PHP_EOL;
                }
            });
            echo '协程id：' . $k . '开启成功' . PHP_EOL;
        }
    }

    //xpath 请求例子
    public function xpathDemo()
    {
        $url = 'http://www.ting56.com/mp3/896.html';
        $html = file_get_contents($url);
        $dom = new \DOMDocument();
        @$dom->loadHTML($html);
        $dom->normalize();
        $xpath = new \DOMXPath($dom);
        $hrefList = $xpath->query("//div[@id='vlink_1']/ul/li/a/@href");
        $href_url = 'http://www.ting56.com';
        for ($i = 0; $i < $hrefList->length; $i++) {
            $href = $hrefList->item($i);
            $html = file_get_contents($href_url . $href->nodeValue);
            var_dump($html);

        }
    }


    public function curl()
    {
        $targetUrl = "http://swoole_api.shuzi88.com/index/index";
        $user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0";
        $ch = curl_init();
        // 关闭ssl认证
        curl_setopt($ch, CURLOPT_PROXY, '123.139.56.238');
        curl_setopt($ch, CURLOPT_PROXYPORT, 9999);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_URL, $targetUrl);
//        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 获取头部信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        $content = curl_exec($ch);
        curl_close($ch);
        var_dump($content);
        return true;


//        $curl = curl_init();
        //设置抓取的url
//        curl_setopt($curl, CURLOPT_URL, $targetUrl);
        //设置头文件的信息作为数据流输出
//        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // 设置请求时间  不超过3秒
//        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
        //执行命令
//        $data = curl_exec($curl);
        // 获取请求后的状态码
//        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //关闭URL请求
//        curl_close($curl);
        //显示获得的数据
//        return $data;
    }


    public function help(array $args): ?string
    {
        // TODO: Implement help() method.
        return '这里是测试命令行';
    }

    public function down_mp3($url, $data = [])
    {
        // curl下载文件
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $mp3 = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno' . curl_error($ch);
        }

        curl_close($ch);
        // 保存文件到指定路径

        return $mp3;
    }

    /**
     * @param $url
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function http_req($url, $data = [], $method = "GET", $cookie = [], $headers = [])
    {
        $httpClient = new HttpClient($url);

//        $httpClient->setTimeout(10);
        if (!empty($cookie)) {
            foreach ($cookie as $k => $v) {
                $httpClient->addCookie($k, $v);
            }
        }
        if (empty($this->headers)) {
            $httpClient->setHeaders($this->headers);
        } else {
            $httpClient->setHeaders($headers);
        };
        if ($method != 'GET') {
            $ret = $httpClient->post($data);
        } else {
            $ret = $httpClient->get($data);
        }
        if ($ret->getErrCode() == 0) {
            return $ret->getBody();
        } else {
            return false;
        }

    }


    /**
     * @param $url string 请求地址
     * @param $fileName string 文件保存路径以及名字
     * @param array $headers
     * @return mixed int 反正请求状态码 0成功
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     *
     */
    public function downloadFile($url, $fileName, $headers = [])
    {
//        $httpClient = new HttpClient($url);
//        if (empty($this->headers)) {
//            $httpClient->setHeaders($this->headers);
//        } else {
//            $httpClient->setHeaders($headers);
//        };
//        $response = $httpClient->download($fileName);
//        Coroutine::sleep(2);
//        return $response;
        $data = parse_url($url);
        $cli = new \Swoole\Coroutine\Http\Client($data['host'], 443, true);
        $cli->set(['timeout' => -1]);
        $cli->setHeaders([
            'Host' => $data['host'],
            "User-Agent" => 'Chrome/49.0.2587.3',
            'Accept' => '*',
            'Accept-Encoding' => 'gzip',
        ]);
        $cli->download($data['path'], $fileName);
        echo $data['host'], $data['path'], ' => ', $fileName, PHP_EOL;
    }


    public function countOff()
    {
        $userModel = new UserModel();
        $result = $userModel->userFindOne('root');
        var_dump($result);
//        var_dump(TextModel::create()->limit(1)->select());
//       $a = TextModel::create()->where(['date'=>'2019-12-14'])->field('news_json,officialid')->select();
    }


    private function mysql_pool_conn()
    {
        $mysqlConf = Config::getInstance()->getConf('MYSQL');
        $config = new \EasySwoole\ORM\Db\Config();
        // 基础配置
        $config->setDatabase($mysqlConf['database']);
        $config->setUser($mysqlConf['user']);
        $config->setPassword($mysqlConf['password']);
        $config->setHost($mysqlConf['host']);

        //连接池配置
        $config->setGetObjectTimeout(3.0); //设置获取连接池对象超时时间
        $config->setIntervalCheckTime(30 * 1000); //设置检测连接存活执行回收和创建的周期
        $config->setMaxIdleTime(15); //连接池对象最大闲置时间(秒)
        $config->setMaxObjectNum(20); //设置最大连接池存在连接对象数量
        $config->setMinObjectNum(5); //设置最小连接池存在连接对象数量
        //创建连接
        DbManager::getInstance()->addConnection(new Connection($config));
        DbManager::getInstance()->addConnection(new Connection($config), 'liuqiang');
    }
}
